/* eslint-disable no-param-reassign */
import { Draw } from 'ol/interaction';
import { createBox, createRegularPolygon } from 'ol/interaction/Draw';
import Polygon from 'ol/geom/Polygon';
import Control from './control';
import drawPointSVG from '../../img/draw_point.svg';
import drawPolygonSVG from '../../img/draw_polygon.svg';
import drawLineSVG from '../../img/draw_line.svg';
import drawCircleSVG from '../../img/draw_circle.svg';
import drawSquareSVG from '../../img/draw_square.svg';
import drawBoxSVG from '../../img/draw_box.svg';
import drawStarSVG from '../../img/draw_star.svg';
import drawplot_CircleSVG from '../../img/drawplot_Circle.svg';
import drawplot_CurveFlagSVG from '../../img/drawplot_CurveFlag.svg';
import drawplot_TextAreaSVG from '../../img/drawplot_TextArea.svg';
import * as PlotTypes from '../control/plot/utils/PlotTypes';
import olPlot from '../control/plot/index';
var InnerPlot = null;

/**
 * Control for drawing features.
 * @extends {ole.Control}
 * @alias ole.DrawControl
 */
class DrawControl extends Control {
  /**
   * @param {Object} [options] Tool options.
   * @param {string} [options.type] Geometry type ('Point', 'LineString', 'Polygon',
   *   'MultiPoint', 'MultiLineString', 'MultiPolygon' or 'Circle').
   *   Default is 'Point'.
   * @param {Object} [options.drawInteractionOptions] Options for the Draw interaction (ol/interaction/Draw).
   * @param {ol.style.Style.StyleLike} [options.style] Style used for the draw interaction.
   */
  constructor(options) {
    let image = null;
    let title = "圆";
    let geometryFunction = null;
    let type = options?.type || 'Point';
    if (options?.type && options?.type.startsWith('plot:')) {
      let tmpType = options?.type.replace('plot:', '').toUpperCase();
      const fun = new Function('type', 'return type.Alias_' + tmpType)(
        PlotTypes,
      );
      title = fun + '[军标]';
      image = DrawControl.setImg(options.type);
    } else {
      switch (options?.type) {
        case 'Square':
          image = drawSquareSVG;
          title = '正方形';
          geometryFunction = createRegularPolygon(4);
          type = 'Circle';
          break;
        case 'Box':
          image = drawBoxSVG;
          title = '矩形';
          geometryFunction = createBox();
          type = 'Circle';
          break;
        case 'Star':
          image = drawStarSVG;
          title = '五角星';
          geometryFunction = DrawControl.geometry2StarFunction;
          type = 'Circle';
          break;
        case 'Circle':
          image = drawCircleSVG;
          title = '圆';
          break;
        case 'Polygon':
          image = drawPolygonSVG;
          title = '多边形';
          break;
        case 'LineString':
          image = drawLineSVG;
          title = '线';
          break;
        default:
          image = drawPointSVG;
      }
    }
    super({
      // title: `Draw ${options?.type || 'Point'}`,
      title: `绘制 ${title}`,
      className: 'ole-control-draw',
      image,
      ...(options || {}),
    });

    this.options = options;
    this.type = type;
    if (options?.type && options?.type.startsWith('plot:')) {
      return;
    }

    /**
     * @type {ol.interaction.Draw}
     * @private
     */
    this.drawInteraction = new Draw({
      type: type || 'Point',
      features: options?.features,
      source: options?.source,
      style: options?.style,
      stopClick: true,
      geometryFunction: geometryFunction,
      ...(options?.drawInteractionOptions || {}),
    });

    this.drawInteraction.on('drawstart', (evt) => {
      this.editor.setDrawFeature(evt.feature);
    });

    this.drawInteraction.on('drawend', () => {
      this.editor.setDrawFeature(null);
    });
  }

  static geometry2StarFunction(coordinates, geometry) {
    const center = coordinates[0];
    const last = coordinates[coordinates.length - 1];
    const dx = center[0] - last[0];
    const dy = center[1] - last[1];
    const radius = Math.sqrt(dx * dx + dy * dy);
    const rotation = Math.atan2(dy, dx);
    const newCoordinates = [];
    const numPoints = 10;
    for (let i = 0; i < numPoints; ++i) {
      const angle = rotation + (i * 2 * Math.PI) / numPoints;
      const fraction = i % 2 === 0 ? 1 : 0.5;
      const offsetX = radius * fraction * Math.cos(angle);
      const offsetY = radius * fraction * Math.sin(angle);
      newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
    }
    newCoordinates.push(newCoordinates[0].slice());
    if (!geometry) {
      geometry = new Polygon([newCoordinates]);
    } else {
      geometry.setCoordinates([newCoordinates]);
    }
    return geometry;
  }
  static setImg(type) {
    let defalutSVG = `
    <svg width="32" height="32" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
    <!-- Created with SVG-edit - http://www.86y.org/demo/svg/-->
      <g class="layer">
          <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">TXT</text>
      </g>
    </svg>
    `;
    let typeName = PlotTypes['Alias_' + type.replace("plot:",'')];
    const realTxt = typeName[0];
    let result = defalutSVG.replace('TXT', realTxt).replace(/\r|\n|> /gi, '');
    result = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(result);
    return result;
  }
  setMap(map) {
    super.setMap(map);
    if (InnerPlot == null) {
      InnerPlot = new olPlot(map, this.options);
    }
  }
  /**
   * @inheritdoc
   */
  activate() {
    if (this.type.startsWith('plot:')) {
      let type = this.type.replace('plot:', '');
      InnerPlot.plotDraw.activate(PlotTypes[type]);
    } else {
      this.map.addInteraction(this.drawInteraction);
    }
    super.activate();
  }

  /**
   * @inheritdoc
   */
  deactivate(silent) {
    if (this.type.startsWith('plot.')) {
      let type = this.type.replace('plot.', '');
      InnerPlot.plotDraw.deactivate(type);
    } else {
      this.map.removeInteraction(this.drawInteraction);
    }
    super.deactivate(silent);
  }
}

export default DrawControl;
